package com.ruoyi.api;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.WxApiLoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.framework.web.service.WxApiTokenService;
import com.ruoyi.wxapp.domain.WxappUsers;
import com.ruoyi.wxapp.service.IWxappUsersService;
import com.ruoyi.wxapp.service.impl.WxappUsersServiceImpl;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Api(tags = "微信小程序-用户接口", description = "用户信息及令牌接口")
@RestController
@RequestMapping("/wxapi/user/")
@Slf4j
public class WxUserController {

    @Autowired
    private WxApiTokenService wxApiTokenService;

    @Autowired
    private IWxappUsersService iWxappUsersService;


    @ApiOperation("用户信息")
    @GetMapping("info")
    public AjaxResult info(HttpServletRequest request) {
        WxApiLoginUser loginUser = wxApiTokenService.getLoginUser(request);
        WxappUsers users = iWxappUsersService.selectWxappUsersById(loginUser.getId());
        log.debug("----------> 用户信息：" + users);

        Map<String, Object> data = new HashMap<>();
        data.put("id", users.getId());
        data.put("openid", users.getOpenid());
        data.put("avatar", users.getAvatar());
        data.put("nickName", users.getNickname());
        data.put("expireTime", new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(loginUser.getExpireTime()));

        return AjaxResult.success(data);
    }

    
    @ApiOperation("更新用户信息")
    @PatchMapping("/info")
    public AjaxResult updateUserProfile(@RequestBody WxappUsers users) {
        int code = iWxappUsersService.updateWxappUsers(users);
        return AjaxResult.success(code);
    }


    @ApiOperation("刷新令牌")
    @PostMapping("token")
    public AjaxResult token(HttpServletRequest request) {
        WxApiLoginUser loginUser = wxApiTokenService.getLoginUser(request);
        wxApiTokenService.refreshToken(loginUser);

        Map<String, Object> data = new HashMap<>();
        data.put("id", loginUser.getId());
        data.put("expireTime", new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(loginUser.getExpireTime()));

        return AjaxResult.success(data);
    }
}
